package com.ffcc.fitness.common.controller;

import com.ffcc.fitness.base.response.JsonResult;
import com.ffcc.fitness.common.service.VerificationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 邮箱验证码控制器
 */
@Slf4j
@RestController
@RequestMapping("/v1/email")
@Api(tags = "邮箱验证码管理")
public class EmailVerificationController {
    
    private final VerificationService verificationService;
    
    // 邮箱正则表达式
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
    
    // 发送间隔限制（秒）
    private static final int SEND_INTERVAL_SECONDS = 60;
    
    // 存储上次发送时间的Map（生产环境建议使用Redis）
    private static final Map<String, Long> lastSendTimeMap = new HashMap<>();
    
    public EmailVerificationController(VerificationService verificationService) {
        this.verificationService = verificationService;
    }
    
    @PostMapping("/send-code")
    @ApiOperation("发送邮箱验证码")
    public JsonResult sendVerificationCode(
            @RequestParam @ApiParam("邮箱地址") String email) {
        
        // 验证邮箱格式
        if (!EMAIL_PATTERN.matcher(email).matches()) {
            return new JsonResult(5002, "邮箱格式不正确");
        }
        
        // 检查发送间隔
        Long lastSendTime = lastSendTimeMap.get(email);
        long currentTime = System.currentTimeMillis();
        if (lastSendTime != null && (currentTime - lastSendTime) < SEND_INTERVAL_SECONDS * 1000) {
            long remainingSeconds = SEND_INTERVAL_SECONDS - (currentTime - lastSendTime) / 1000;
            return new JsonResult(5002, "请等待 " + remainingSeconds + " 秒后再试");
        }
        
        try {
            // 发送验证码
            boolean sendResult = verificationService.sendEmailVerificationCode(email);
            
            if (sendResult) {
                // 记录发送时间
                lastSendTimeMap.put(email, currentTime);
                log.info("邮箱验证码发送成功: email={}", email);
                return JsonResult.ok("验证码发送成功，请查收邮件");
            } else {
                return new JsonResult(5001, "验证码发送失败，请稍后重试");
            }
            
        } catch (Exception e) {
            log.error("发送邮箱验证码异常: email={}", email, e);
            return new JsonResult(5001, "发送验证码失败");
        }
    }
    
    @PostMapping("/verify-code")
    @ApiOperation("验证邮箱验证码")
    public JsonResult verifyCode(
            @RequestParam @ApiParam("邮箱地址") String email,
            @RequestParam @ApiParam("验证码") String code) {
        
        // 验证邮箱格式
        if (!EMAIL_PATTERN.matcher(email).matches()) {
            return new JsonResult(5002, "邮箱格式不正确");
        }
        
        // 验证验证码格式
        if (code == null || !code.matches("\\d{6}")) {
            return new JsonResult(5002, "验证码格式不正确");
        }
        
        try {
            // 验证验证码
            boolean isValid = verificationService.verifyEmailCode(email, code);
            
            if (isValid) {
                log.info("邮箱验证码验证成功: email={}", email);
                return JsonResult.ok("验证码验证成功");
            } else {
                return new JsonResult(5002, "验证码错误或已过期");
            }
            
        } catch (Exception e) {
            log.error("验证邮箱验证码异常: email={}, code={}", email, code, e);
            return new JsonResult(5001, "验证码验证失败");
        }
    }
}
